package com.kxn.multi.module.service.base;

import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxn.multi.module.common.pojo.ApiResult;
import com.kxn.multi.module.service.util.SpringUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

public abstract class BaseController<T extends ServiceImpl, M> {


    /**
     * 获取service的Class
     *
     * @return
     */
    protected Class<T> currentServiceClass() {
        return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseController.class, 0);
    }

    /**
     * 获取Entity的Class
     *
     * @return
     */
    protected Class<M> currentEntityClass() {
        return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseController.class, 1);
    }

    /**
     * 获取默认Service
     *
     * @return
     */
    public T getDefaultService() {
        return SpringUtil.getBean(this.currentServiceClass());
    }

    @ApiOperation("获取详情")
    @GetMapping("/{id}")
    public ApiResult detail(@PathVariable Integer id) {
        T service = getDefaultService();
        M model = (M) service.getById(id);
        return ApiResult.success(model);
    }

    @ApiOperation("添加操作")
    @PostMapping("/create")
    public ApiResult insert(@RequestBody M model) {
        T service = getDefaultService();
        service.save(model);
        return ApiResult.success(model);
    }

    @ApiOperation("删除操作")
    @PostMapping("/delete/{id}")
    public ApiResult delete(@PathVariable Integer id) {
        T service = getDefaultService();
        service.removeById(id);
        return ApiResult.success();
    }

    @ApiOperation("更新操作")
    @PostMapping("/update/{id}")
    public ApiResult update(@PathVariable Integer id, @RequestBody M model) {
        T service = getDefaultService();
        M oldData = (M) service.getById(id);
        if (oldData == null) {
            ApiResult.error("数据不存在");
        }
        service.updateById(model);
        return ApiResult.success(model);
    }

}